package com.yukefms.rule.state;

import com.yukefms.engine.running.EventCode;
import com.yukefms.engine.running.RunningContext;
import com.yukefms.engine.running.RunningEvent;
import com.yukefms.jointpoint.BodyPointCloud;
import com.yukefms.rule.interfaces.BARule;
import com.yukefms.rule.interfaces.BAStageRule;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * @Description
 * @Author Ping
 * @Date 2021/6/29 10:25
 **/
public class UnMatchedState extends BARuleState {
    public static Logger logger = LogManager.getLogger(UnMatchedState.class);

    public UnMatchedState(final BAStageRule relatedRule) {
        super(relatedRule);
    }

    @Override
    public void doReaction(BodyPointCloud pointCloud, RunningContext context) {
        logger.error("the Rule-{} is UNMATCHED for [TRIAL] {}.", this.relatedRule.ruleName(),
                                    context.getTrialoutCounter().getCurNum() ) ;
        context.updateTrialoutCounter();


        if (context.isTrialout()) {
            logger.error("the Rule-{} is FAILED since TRIAL-OUT.", this.relatedRule.ruleName()) ;
            this.relatedRule.setRuleState(RuleStateFlyWeight.getState(RuleStateFlyWeight.FAILED));
//            context.notifyTrialoutEventListener(RunningEvent.buildEvent(EventCode.TRIAL_OUT, this.relatedRule.ruleName())
//                    ,context);
           context.notifyRunningEventListener(EventCode.FAILED,
                    this.relatedRule.ruleName(),
                    this.relatedRule.getViolatedDesc(this.relatedRule.currentStage().getName()));
            // send unfailed infor,and the state was transited
            // to the FAILED, but withou sending failed infor, which
            // would result in a conflict state.
            //
            this.relatedRule.doReaction(pointCloud, context);
        } else {

            // reset the rule to the frist stage.
            // trial it again.
            relatedRule.redo() ;
             logger.error("[TRIAL] {}: the Rule was RESET. ",context.getTrialoutCounter().getCurNum() ) ;
            logger.error("Current Stage {}. ", this.relatedRule.currentStage().getName() ) ;
            context.resetTimer();
            context.resetInputErrorCounter();
            context.resetInvariantFailCounter();
            this.relatedRule.setRuleState(RuleStateFlyWeight.getState(RuleStateFlyWeight.IN_ACTIVATED));
        }
        // empty caching structure
        context.resetCachingStructure();

    }

}
